package com.skymxc.skin

import android.content.Context
import android.content.res.ColorStateList
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.Log

/**
 * <p>
 *
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/9/20  10:13 下午
 */
class SkinResources private constructor(context:Context){

    private val TAG = "SkinResources"
    companion object {
        @Volatile
        private var _instance:SkinResources?=null

       internal fun init(context: Context){
            _instance = SkinResources(context)
        }
        fun getInstance() = _instance!!
    }

    //APP 原始资源
    private val appResources:Resources = context.resources

    //皮肤包资源
    private var skinResources:Resources? = null

    private var mSkinPkgName :String =""
    private var isDefaultSkin =true

    fun reset(){
        mSkinPkgName = ""
        isDefaultSkin =true
        skinResources = null
    }

    fun applySkin(resource:Resources,pkgName:String){
        skinResources = resource
        mSkinPkgName = pkgName
        isDefaultSkin = resource==null || TextUtils.isEmpty(pkgName)
        Log.i(TAG, "applySkin: isDefaultSkin->$isDefaultSkin")
    }

    /**
     * 通过原始资源ID 获取到对应资源名称，
     * 然后通过资源名称在皮肤包里找到对应的资源ID返回
     * @param resId 原始资源ID
     */
    fun getIdentifier(resId: Int): Int {
        if (isDefaultSkin) return resId
        val resourceName = appResources.getResourceEntryName(resId)
        val resourceTypeName = appResources.getResourceTypeName(resId)
        val identifier = skinResources?.getIdentifier(resourceName, resourceTypeName, mSkinPkgName)
        return identifier ?: resId
    }

    /**
     * 输入主APP的ID，到皮肤APK文件中去找到对应ID的颜色值
     */
    fun getColor(resId:Int):Int{
        if (isDefaultSkin) return appResources.getColor(resId)
        val skinId = getIdentifier(resId)
        if (skinId==0) return appResources.getColor(resId)
        Log.i(TAG, "getColor: resid:$resId VS skinId:$skinId")
        return skinResources!!.getColor(skinId)
    }

    fun getDrawable(resId:Int):Drawable{
        if (isDefaultSkin) return appResources.getDrawable(resId)
        val skinId = getIdentifier(resId)
        if (skinId==0) return appResources.getDrawable(resId)

        return skinResources!!.getDrawable(skinId)
    }


    fun getColorStateList(resId:Int): ColorStateList {
        if (isDefaultSkin) return appResources.getColorStateList(resId)
        val skinId = getIdentifier(resId)
        if (skinId==0) return appResources.getColorStateList(resId)

        return skinResources!!.getColorStateList(skinId)
    }

    /**
     * 可能是Color 也可能是drawable
     */
    fun getBackground(resId:Int):Any{
        val resTypeName = appResources.getResourceTypeName(resId)
       return if ("color"==resTypeName){
            getColor(resId)
        }else{
            getDrawable(resId)
        }

    }


}